package edu.spec.pms.web;

import org.madgecko.basic.model.SystemContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class SystemContextFilter implements Filter{
	private Integer pageSize;

	// filter的init方法在系统启动时执行，过来时不执行
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		try{
			pageSize = Integer.parseInt(filterConfig.getInitParameter("pageSize"));
//			System.out.println("pageSize------------------------------------------------");
//			System.out.println(pageSize);
		}catch(NumberFormatException nfe){
			pageSize = 15;
			System.out.println(pageSize);
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		Integer offset = 0;
		try{
			// 由于ExtJS使用的分页变量与JSP pager的分页变量的名称不同，所以需做判断
			String _startStr = request.getParameter("start");
			if(null==_startStr){
				_startStr = request.getParameter("pager.offset");
			}
			offset = Integer.parseInt(_startStr);
			System.out.println("offset------------------------------------------------");
			System.out.println(offset);

			String _limitStr = request.getParameter("limit");
			if(null!=_limitStr){
				pageSize = Integer.parseInt(_limitStr);
			}
		}catch(NumberFormatException nfe){
			offset = 0;
		}
		
		try{
			SystemContext.setPageOffset(offset);
			SystemContext.setPageSize(pageSize);
			SystemContext.setOrder(request.getParameter("order"));
			SystemContext.setSort(request.getParameter("sort"));
			SystemContext.setRealPath(((HttpServletRequest) request).getSession().getServletContext().getRealPath("/"));
			chain.doFilter(request, response);
		}finally{
			SystemContext.removePageOffset();
			SystemContext.removePageSize();
			SystemContext.removeOrder();
			SystemContext.removeSort();
		}
	}

	@Override
	public void destroy() {
		
	}
	
}
